<?php
//$Id: functions.php 9 2009-04-26 06:35:12Z bole.Chen $

// Loads controllers
function loads() {
    $args = func_get_args();
    foreach ($args as $arg) include_once (CTLS.strtolower($arg).'.php');
}

// Loads Plugins
function load_plugins() {
    $args = func_get_args();
    foreach ($args as $arg) {
        $pfile = ROOT.'plugins'.DS.strtolower($arg).'.php';
        include_once ($pfile);
    }
}

// Get the Controller if we need
function &getController($ctl, $instance=true) {
    global $RUNTIME;
    if (!$RUNTIME['START']) $RUNTIME['START'] = getmicrotime();

    @ob_start();
    $ctlfile = CTLS.$ctl.'.php';
    if (!file_exists($ctlfile)) die("<b>miss controller file:</b> $ctlfile");
    require_once $ctlfile;
    $ctlclass = $ctl.'Controller';
    if (!class_exists("$ctlclass")) die("<b>miss cntroller class:</b> $ctlclass");

    return $instance ? new $ctlclass : true;
}

// Fix the Fuck Magic Quotes
function array_map_recursive($callback, $array) {
    $r = array();
    if (is_array($array))
        foreach($array as $key => $value)
            $r[$key] = is_scalar($value) ?
                $callback($value) :
                array_map_recursive($callback, $value);
    return $r;
}

function array_stripslashes($array) {
    return array_map_recursive('stripslashes', $array);
    //return array_map_recursive('stripslashes_quote', $array);
}

// replace the double quote
function stripslashes_quote($str) {
    return stripslashes(str_replace('"', '&quot;', $str));
}

if (get_magic_quotes_gpc()) {
    $_GET        = array_stripslashes($_GET);
    $_POST       = array_stripslashes($_POST);
    $_REQUEST    = array_stripslashes($_REQUEST);
    $_COOKIE     = array_stripslashes($_COOKIE);
}

function getmicrotime(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
}

function status_header($num) {
    // Set status text
    switch ($num) {
    case 200: $status = "OK"; break;
    case 301: $status = "Moved Permanently"; break;
    case 404: $status = "Not Found"; break;
    default: return FALSE;
    }

    // BC code for PHP < 4.3.0
    @header("HTTP/1.1 $num $status");
    @header("Status: $num $status", TRUE, $num);

    return true;
}

//模拟 iconv
if (!function_exists('iconv')) {
    function iconv($from, $to, $str) {
        uses('ctc');

        if (strtoupper($from) == 'UTF-8') $from = 'UTF8';
        if (strtoupper($to) == 'UTF-8') $to = 'UTF8';
        $from = strtoupper($from);
        $to = strtoupper($to);

        $ctc = new ctc($str, $from, $to);
        return $ctc->ConvertIT();
    }
}

//For Plugin
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
    global $lp_action;

    // check that we don't already have the same filter at the same priority
    if ( isset($lp_action[$tag]["$priority"]) ) {
        foreach($lp_action[$tag]["$priority"] as $filter) {
            // uncomment if we want to match function AND accepted_args
            // if ( $filter == array($function, $accepted_args) ) {
            if ( $filter['function'] == $function_to_add ) {
                return true;
            }
        }
    }

    // So the format is lp_action['tag']['array of priorities']['array of ['array (functions, accepted_args)]']
    $lp_action[$tag]["$priority"][] = array('function'=>$function_to_add, 'accepted_args'=>$accepted_args);
    return true;
}

function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
    global $lp_action;

    // rebuild the list of filters
    if ( isset($lp_action[$tag]["$priority"]) ) {
        foreach($lp_action[$tag]["$priority"] as $filter) {
            if ( $filter['function'] != $function_to_remove ) {
                $new_function_list[] = $filter;
            }
        }
        $lp_action[$tag]["$priority"] = $new_function_list;
    }
    return true;
}

function do_filters($tag, $string) {
    global $lp_action;

    $args = array_slice(func_get_args(), 2);

    merge_action($tag);

    if ( !isset($lp_action[$tag]) ) {
        return $string;
    }
    foreach ($lp_action[$tag] as $priority => $functions) {
        if ( !is_null($functions) ) {
            foreach($functions as $function) {

                $all_args = array_merge(array($string), $args);
                $function_name = $function['function'];
                $accepted_args = $function['accepted_args'];

                if ( $accepted_args == 1 )
                    $the_args = array($string);
                elseif ( $accepted_args > 1 )
                    $the_args = array_slice($all_args, 0, $accepted_args);
                elseif ( $accepted_args == 0 )
                    $the_args = NULL;
                else
                    $the_args = $all_args;

                $string = call_user_func_array($function_name, $the_args);
            }
        }
    }
    return $string;
}

function do_action($tag, $arg="") {
    global $lp_action;

    $extra_args = array_slice(func_get_args(), 2);
    if ( is_array($arg) )
        $args = array_merge($arg, $extra_args);
    else
        $args = array_merge(array($arg), $extra_args);

    if (!$lp_action[$tag]) return;

    merge_action($tag);

    foreach ($lp_action[$tag] as $priority => $functions) {
        if ( !is_null($functions) ) {
            foreach($functions as $function) {

                $function_name = $function['function'];
                $accepted_args = $function['accepted_args'];

                if ( $accepted_args == 1 ) {
                    if ( is_array($arg) )
                        $the_args = $arg;
                    else
                        $the_args = array($arg);
                } elseif ( $accepted_args > 1 ) {
                    $the_args = array_slice($args, 0, $accepted_args);
                } elseif ( $accepted_args == 0 ) {
                    $the_args = NULL;
                } else {
                    $the_args = $args;
                }

                call_user_func_array($function_name, $the_args);
            }
        }
    }
}

function merge_action($tag) {
    global $lp_action;

    if ( isset($lp_action['all']) ) {
        foreach ($lp_action['all'] as $priority => $functions) {
            if ( isset($lp_action[$tag][$priority]) )
                $lp_action[$tag][$priority] = array_merge($lp_action['all'][$priority], $lp_action[$tag][$priority]);
            else
                $lp_action[$tag][$priority] = array_merge($lp_action['all'][$priority], array());
            $lp_action[$tag][$priority] = array_unique($lp_action[$tag][$priority]);
        }
    }

    if (isset($lp_action[$tag])) ksort($lp_action[$tag]);
}

function maybe_unserialize($original) {
    if ( false !== $gm = @ unserialize($original) )
        return $gm;
    else
        return $original;
}

function shutdown_action_hook() {
    //do_action('shutdown');
    if (function_exists('cache_close')) cache_close();
}

register_shutdown_function('shutdown_action_hook');

//sql查询数统计
function CountQueries() {
    global $CountQueries;
    $CountQueries++;
}

function CountCachedQueries() {
    global $CountCachedQueries;
    $CountCachedQueries++;
}

//获取 DB 类
function getDB($debug=false) {
    global $__m;

    //if (is_object($__m)) return $__m;

    uses('model');
    $__m = new Model;
    $__m->dbconnect($debug);
    return $__m->db;
}

//获取表名
function getTable($table='') {
    global $__m;

    if (!is_object($__m)) getDB();

    if ($table)
        return $__m->table[$table];
    else
        return $__m->table;
}

function is_home() {
    return $_SERVER['PHP_SELF'] == '/index.php' || preg_match('|/F/.{3,}|', $_SERVER['REQUEST_URI']);
}

/**
 * 快递单号查询
 *
 * @param string $name 快递名称
 * @param string $no 单号
 * @access public
 * @return string $url 查询地址
 */
function post_query_link($name, $no, $text='物流状态查询') {
    if ($no) {
        if (strpos($name, '顺丰') !== false) $url = 'http://www.sf-express.com/tabid/68/Default.aspx';
        if (strpos($name, '申通') !== false) $url = 'http://www.sto.cn/';
        if (strpos($name, '小红马') !== false) $url = 'http://www.ponyex.com.cn/result.asp?ID='.strtoupper($no);
        if (strpos($name, '中通') !== false) $url = 'http://www.zto.cn/bill.asp?ID='.$no;
        if (strpos($name, '全一') !== false) $url = 'http://www.apex100.com/search/TransitControl?orgid='.$no;
        if (strpos($name, '圆通') !== false) $url = 'http://www.yto56.net.cn/html/sql.asp?NumberText='.$no;
        if (strpos($name, 'EMS') !== false) $url = 'http://www.ems.com.cn/qcgzOutQueryAction.do?reqCode=gotoSearch';
        if ($url) return "<a href='$url' target='_blank'>$text</a>";
        return '';
    }
}
?>
